var layer = layui.layer //弹层
    ,table = layui.table //表格
    form = layui.form,$ = layui.jquery,changeList=[],laydate = layui.laydate;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

layer.ready(function () {
    $.ajax({
        url:"otherOutStock/getAllUserInfo",
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    $('#salesmanCode').append(new Option(data.data[i].name, data.data[i].code));
                }
                form.render('select');
            }
        }
    });
});

let initData = [];
table.render({
    elem: '#shipmentplan'
    ,data:initData
    ,url:"otherInStock/import/carryPlanByPage"
    ,cols: [[
        {checkbox: true, sort : true,title:'选择'}
        ,{field:'shipmentNo', title:'出运单号',sort:true}
        ,{field:'salesContractNo.', title:'销售合同号',sort:true}
        ,{field:'companyName', title:'签约单位',sort:true}
        ,{field:'createTime', title:'创建日期',sort:true}
        ,{field:'shipmentDate', title:'出运日期',sort:true}
    ]]
    ,id: 'shipmentplantableid'
    ,height: 300
    ,page: true
    ,done: function (res, curr, count) {
        table.render({
            elem: '#product'
            ,url:"otherInStock/import/carryPlanProduct"
            ,cols: [[
                {checkbox: true, sort : true,title:'选择'}
                ,{field:'productCode', title:'产品编码', sort: true}
                ,{field:'specificationCode', title:'规格编码', sort: true}
                ,{field:'specificationExplanation', title:'规格说明', sort: true}
                ,{field:'productCname', title:'中文名称', sort: true}
                ,{field:'productEname', title:'英文名称', sort: true}
                ,{field:'totalQuantity', title:'数量', sort: true}
                ,{field:'referenceQuantity', title:'剩余数量', sort: true}
                ,{field:'productUnit', title:'单位', sort: true}
                ,{field:'netWeight',title : '净重',sort : true}
                ,{field:'grossWeight',title : '毛重',sort : true}
                ,{field:'purchaseNo', title:'出运计划号', sort: true}
            ]]
            ,id: 'producttableid'
            ,where: {
                id:res.data.length == 0 ? "":res.data[0].id //默认第一条信息，数据为空则id为空
            }
            ,height: 400
            ,done:function () {
                $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
            }
        });
    }
});

//监听主表复选框
table.on('checkbox(shipmentplantable)', function (data) {
    let id = data.data.id;
    table.reload('producttableid', {
        where: {
            id:id
        },
        done: function (res, curr, count) {
            let child = $("#product").next().find('tbody input[type="checkbox"]');
            child.each(function(index, item){
                item.checked = data.checked;
            });
            if(data.checked){
                for(var i = 0; i < res.data.length; i++){
                    changeList.push(res.data[i]);
                }
            }else{
                if(changeList.length > 0){
                    for(var i = 0; i < res.data.length; i++){
                        deleteData(res.data[i]);
                    }
                }
            }
            form.render('checkbox');

            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
        }
    }, 'data');
});

function deleteData(data){
    let id = data["planDetailId"];
    for(var j = 0; j < changeList.length; j++){
        if (changeList[j]["planDetailId"] == id) {
            changeList.splice(j, 1); // 将使后面的元素依次前移，数组长度减1
            j--; // 如果不减，将漏掉一个元素
        }
    }
}

//监听子复选框
table.on('checkbox(producttable)', function (obj) {
    if (obj.checked) {
        changeList.push(obj.data);
    } else {
        for (let index in changeList) {
            if (changeList[index]["planDetailId"] == obj.data["planDetailId"]) {
                changeList.splice(index,1);
            }
        }
    }
    form.render('checkbox');
});

//单击行事件
table.on('row(shipmentplantable)', function (obj) {
    let id = obj.data.id;
    table.reload('producttableid', {
        where: {
            id:id
        },
        parseData: function (res) {
            if (changeList) {
                for (let i in res.data) {
                    for (let j in changeList) {
                        if (changeList[j]["planDetailId"] == res.data[i]["planDetailId"]) {
                            res.data[i].LAY_CHECKED = 'true';
                        }
                    }
                }
            }
            return res;
        },
        done: function (res, curr, count) {
            $("th .layui-table-cell.laytable-cell-checkbox").html("选择");
        }
    }, 'data');
});

form.on('submit(submitform)', function(data){
    table.reload('shipmentplantableid', {
        page: {
            curr: 1 //重新从第 1 页开始
        }
        ,where: data.field
    }, 'data');
    return false;
});

$("#choose").on("click",function () {
    if(changeList.length == 0){
        layer.msg("请选择数据")
    }else{
        //产品明细数据
        let oldData =  parent.table.cache["storageproductstableid"];
        $.each(changeList, function (index, value) {
            //剔除重复数据
            let flag = true;
            if(oldData.length > 0){
                for(var i = 0; i < oldData.length; i++){
                    let sameFlag = oldData[i]["planDetailId"] != "undefined" && oldData[i]["planDetailId"] == changeList[index]["planDetailId"];
                    if(sameFlag){
                        flag = false;
                        break;
                    }
                }
            }
            if(flag){
                //不存在重复数据,添加数据
                let tempData = changeList[index];
                tempData["productNum"] = 0;
                tempData["warehouseName"] = "";
                tempData["warehouseCode"] = "";
                tempData["tempId"] = GenNonDuplicateID(3) + (index+1)
                oldData.push(tempData);
            }
        });

        //重载产品明细表单
        parent.table.reload('storageproductstableid', {data:oldData});

        //执行接口
        layer.msg("保存成功", {icon: 6});
        setTimeout(function () {
            //保存成功则关闭此页面
            let index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        },)
    }
})


$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
})

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}

//生成临时id
function GenNonDuplicateID(randomLength){
    return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}